package com.idormy.sms.forwarder.utils;

import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.idormy.sms.forwarder.SenderActivity.NOTIFY;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.gzuliyujiang.oaid.DeviceIdentifier;
import com.idormy.sms.forwarder.MainActivity;
import com.idormy.sms.forwarder.MyApplication;

public class SenderWebNotifyMsg {

    static String TAG = "SenderWebNotifyMsg";

    public static void sendMsg(final Handler handError, String token, String secret, String from, String content) throws Exception {
        Log.i(TAG, "sendMsg token:" + token + " from:" + from + " content:" + content);

        if (token == null || token.isEmpty()) {
            return;
        }
        Map<String, String> result = new HashMap<>();
        result.put("from", from);
        result.put("content", content);
        result.put("deviceId", DeviceIdentifier.getGUID(MyApplication.getContext()));

        //MediaType mediaType = MediaType.parse("text/plain");
        String url = token;
        if(url.contains("?")){
            String[] params = url.split("[?]", 2);
            if(params != null && params.length == 2){
                url = params[0];
                String param = params[1];
                if(param != null && !param.isEmpty()){
                    String[] arrs = param.split("&");
                    for (String str : arrs) {
                        if(str.contains("=")){
                            String[] arr = str.split("=", 2);
                            if(arr != null && arr.length == 2){
                                result.put(arr[0], arr[1]);
                            }
                        }
                    }
                }
            }
        }
        if (secret != null && !secret.isEmpty()) {
            String sign = PaymentUtil.sortSign(result, secret);
            result.put("sign", sign);
        }

        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for(String key : result.keySet()){
            String value = result.get(key);
            builder.addFormDataPart(key, value);
        }
        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .build();
//        Response response = client.newCall(request).execute();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Log.d(TAG, "onFailure：" + e.getMessage());

                if (handError != null) {
                    android.os.Message msg = new android.os.Message();
                    msg.what = NOTIFY;
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("state", false);
                    //bundle.putString("DATA", "发送失败：" + e.getMessage());
                    msg.setData(bundle);
                    handError.sendMessage(msg);
                }

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseStr = response.body().string();
                int code = response.code();
                Log.d(TAG, "Code：" + String.valueOf(code) + responseStr);
                if (handError != null) {
                    android.os.Message msg = new android.os.Message();
                    msg.what = NOTIFY;
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("state", false);
                    if(code == 200 && JsonUtils.isJson(responseStr)){
                        JSONObject jsonObject = JSON.parseObject(responseStr);
                        if(jsonObject.containsKey("code")
                                && "200".equals(jsonObject.getString("code"))
                                && jsonObject.containsKey("data")){
                            Object data = jsonObject.get("data");
                            if((data instanceof Boolean && ((Boolean) data) == true)
                                    || (data instanceof String && "true".equals(data))){
                                bundle.putBoolean("state", true);
                            }
                        }
                    }
                    //bundle.putString("DATA", "发送状态：" + responseStr);
                    msg.setData(bundle);
                    handError.sendMessage(msg);
                    Log.d(TAG, "Coxxyyde：" + String.valueOf(code) + responseStr);
                }

            }
        });
    }
}
